<!-- filepath: frontend/src/components/Register.vue -->
<template>
  <div class="register-form-container">
    <h2>注册</h2>
    <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" status-icon @submit.prevent="handleRegister">
      <el-form-item prop="username">
        <!-- 添加 placeholder -->
        <el-input
          v-model="registerForm.username"
          placeholder="用户名"
          size="large"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="email">
        <!-- 确保有 placeholder -->
        <el-input
          v-model="registerForm.email"
          placeholder="邮箱 (可选)"
          size="large"
          :prefix-icon="Message"
        />
      </el-form-item>
      <el-form-item prop="password">
        <!-- 添加 placeholder -->
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="密码"
          show-password
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <!-- 添加 placeholder -->
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="确认密码"
          show-password
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="loading" style="width: 100%;">
          注册
        </el-button>
      </el-form-item>
      <div class="switch-auth-mode">
        已有账户？ <span @click="$emit('switch-to-login')">立即登录</span>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Message, Lock } from '@element-plus/icons-vue';

const emit = defineEmits(['register-success', 'switch-to-login']);

// 将 registerFormRef 移到函数外部，作为组件级别的引用
const registerFormRef = ref(null);

const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
});

const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

const loading = ref(false);

const handleRegister = async () => {
  if (!registerFormRef.value) {
    console.error('Form reference not found!');
    return;
  }

  registerFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写所有必填项');
      return;
    }
    loading.value = true;
    let response;
    try {
      response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: registerForm.value.username,
          email: registerForm.value.email,
          password: registerForm.value.password,
        }),
      });

      if (!response.ok) {
        let errorMsg = `注册失败，状态码: ${response.status}`;
        try {
          const errorData = await response.json();
          errorMsg = errorData.error || errorMsg;
        } catch (parseError) {
          console.warn("Could not parse error response as JSON:", response.statusText);
          errorMsg = `注册失败: ${response.statusText || response.status}`;
        }
        throw new Error(errorMsg);
      }

      const data = await response.json();

      if (response.ok) {
        const token = data.access_token;
        if (!token || typeof token !== 'string') {
          ElMessage.error('注册成功，但服务器响应格式错误');
          return;
        }
        console.log("Register.vue: Emitting register-success event with data:", { token, user: data.user });
        emit('register-success', { token, user: data.user });
      } else {
        ElMessage.error('注册失败');
      }

    } catch (error) {
      console.error('Register error:', error);
      if (error instanceof SyntaxError && response && response.ok) {
        ElMessage.error('注册成功，但服务器响应格式错误');
      } else {
        ElMessage.error(error.message || '注册时发生未知错误');
      }
    } finally {
      loading.value = false;
    }
  });
};
</script>

<style scoped>
.register-form-container {
  width: 100%; /* 确保填满父容器 */
}
</style>

